import 'package:shared_preferences/shared_preferences.dart';

class SPUtil {
  static late SharedPreferences _prefs;

  /// 初始化
  static Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  /// 存储数据
  static Future<bool> set(String key, dynamic value) {
    if (value is String) return _prefs.setString(key, value);
    if (value is int) return _prefs.setInt(key, value);
    if (value is bool) return _prefs.setBool(key, value);
    if (value is double) return _prefs.setDouble(key, value);
    if (value is List<String>) return _prefs.setStringList(key, value);
    throw ArgumentError('Unsupported value type: ${value.runtimeType}');
  }

  /// 获取数据
  static dynamic get(String key, [dynamic defaultValue]) {
    if (!_prefs.containsKey(key)) return defaultValue;
    return _prefs.get(key) ?? defaultValue;
  }

  /// 获取字符串
  static String getString(String key, [String defaultValue = '']) {
    return _prefs.getString(key) ?? defaultValue;
  }

  /// 获取布尔值
  static bool getBool(String key, [bool defaultValue = false]) {
    return _prefs.getBool(key) ?? defaultValue;
  }

  /// 获取整数
  static int getInt(String key, [int defaultValue = 0]) {
    return _prefs.getInt(key) ?? defaultValue;
  }

  /// 获取浮点数
  static double getDouble(String key, [double defaultValue = 0.0]) {
    return _prefs.getDouble(key) ?? defaultValue;
  }

  /// 获取字符串列表
  static List<String> getStringList(String key, [List<String> defaultValue = const []]) {
    return _prefs.getStringList(key) ?? defaultValue;
  }

  /// 删除数据
  static Future<bool> remove(String key) {
    return _prefs.remove(key);
  }

  /// 清空所有数据
  static Future<bool> clear() {
    return _prefs.clear();
  }
}